package com.kly.order.mapper;

import cn.hutool.json.JSONUtil;
import com.kly.dto.ProductCategoryDto;
import com.kly.order.db.entity.ProductCategoryEntity;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;

import java.util.ArrayList;
import java.util.List;

@Mapper(componentModel = "spring")
public interface ProductCategoryMapper {
    @Mapping(source = "categoryDesc", target = "subscriptions", qualifiedByName = "toJavaBean")
    ProductCategoryDto toDto(ProductCategoryEntity productCategory);

    @Named("toJavaBean")
    default List<ProductCategoryDto.Subscriptions> toJavaBean(String categoryDesc) {
        if (categoryDesc.startsWith("[")) {
            return JSONUtil.toList(JSONUtil.parseArray(categoryDesc), ProductCategoryDto.Subscriptions.class);
        } else {
            List<ProductCategoryDto.Subscriptions> list = new ArrayList<>();
            list.add(JSONUtil.toBean(categoryDesc, ProductCategoryDto.Subscriptions.class));
            return list;
        }

    }

}
